package com.etc.order.consumer.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AuthFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);
    private static final String[] allowed = new String[]{
            "css", "js", "ico", "png", "jpg", "login"
    };
    private static HttpSession session;

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        session = ((HttpServletRequest)request).getSession();
        if (session.getAttribute("userInfo") != null) {
            chain.doFilter(request, response);
        } else {
            for (String s : allowed) {
                if (((HttpServletRequest) request).getRequestURI().contains(s)) {
                    chain.doFilter(request, response);
                    return;
                }
            }
            ((HttpServletResponse)response).setStatus(403);
            request.getRequestDispatcher("/403").forward(request, response);
        }
    }

    public static HttpSession getSession() {
        return session;
    }

    @Override
    public void destroy() {

    }
}
